package com.cslc.mp.service;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.cslc.mp.bean.WechatUser;
import com.cslc.mp.bean.message.RespTextMessage;
import com.cslc.mp.bean.message.custommessage.CustomMessage;
import com.cslc.mp.bean.message.custommessage.Text;
import com.cslc.mp.constant.MpInfo;
import com.cslc.mp.dao.DAOFactory;
import com.cslc.mp.dao.vo.User;
import com.cslc.mp.util.MessageUtil;
import com.cslc.mp.util.SignUtil;

/**
 * 请求与相应消息的服务类
 * @author keliangliang
 *
 */
public class MessageService {
	private static Logger logger = Logger.getLogger(MessageService.class.getName());
	static final String SUBSCRIBE_MSG_HEADER = "您好！欢迎关注中国体育彩票官方微信故障申告微信账号：";
	
	static final String SUBSCRIBE_MSG_BODY = "绑定账号后，您将会：" + "\n" + 
			"1.实时上传您当前遇到的故障" + "\n" +
			"2.第一时间回馈并解决您的问题" + "\n";
	static final String BIND_TIPS = "绑定小贴士：\n" +
			"1.在您的销售终端点击生成二维码\n" +
			"2.返回微信主页面\n" + 
			"3.点击右上角+扫一扫";
	static final String NEWLINE = "\r\n";
	/**
	 * 处理微信发来的请求
	 * @param request
	 * @return
	 */
	public static String processRequest(HttpServletRequest request) {
		 String respMessage = null;  
	        try {  
	            // 默认返回的文本消息内容  
	            String respContent = "请求处理异常，请稍候尝试！";  
	  
	            // xml请求解析  
	            Map<String, String> requestMap = MessageUtil.parseXml(request);  
	            
	            // 发送方帐号（open_id）  
	            String fromUserName = requestMap.get("FromUserName");  
	            // 公众帐号  
	            String toUserName = requestMap.get("ToUserName");  
	            // 消息类型  
	            String msgType = requestMap.get("MsgType");
	            //事件类型
	            String event = requestMap.get("Event");
	            logger.debug("发送方账号：" + fromUserName);
	            logger.debug("公众账号：" + toUserName);
	            logger.debug("消息类型：" + msgType);
	            logger.debug("事件类型： " + event);
	            // 回复文本消息  
	            RespTextMessage textMessage = new RespTextMessage();  
	            textMessage.setToUserName(fromUserName);  
	            textMessage.setFromUserName(toUserName);  
	            textMessage.setCreateTime(new Date().getTime());  
	            textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);  
	            textMessage.setFuncFlag(0);  
	  
	            // 文本消息  
	            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {  
	            	
	            	//接收到的消息内容
	            	String content = requestMap.get("Content");
	            	
	            	//进入客服接口，测试客服接口
	            	if(content.equals("你好")) {
	            		CustomMessage message = new CustomMessage();
	            		Text text = new Text();
	            		String str = "客服接口测试：已接入客服系统，接下来您发送的消息会自动转给客服，客服在48小时内可以无限制给您发送消息";
	            		message.setTouser(fromUserName);
	            		message.setMsgtype("text");
	            		text.setContent(str);
	            		message.setText(text);
	            		//48小时内可以无限制发送
	            		CoreServiceFactory.getInstance().customMessageSend(message);
	            		CoreServiceFactory.getInstance().customMessageSend(message);
	            		CoreServiceFactory.getInstance().customMessageSend(message);
	            		respContent = null;
	            	}
	            	else 
	            	respContent = "客服接口测试：输入你好，可接入客服系统";
	            }  
	            // 图片消息  
	            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {  
	                String picUrl = requestMap.get("PicUrl");
	                String mediaId = requestMap.get("MediaId");
	                logger.debug("PicUrl: " + picUrl);
	                logger.debug("MediaId: " + mediaId);
	            	respContent = "您发送的是图片消息！";  
	            }  
	            // 地理位置消息  
	            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {  
	                respContent = "您发送的是地理位置消息！";  
	            }  
	            // 链接消息  
	            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {  
	                respContent = "您发送的是链接消息！";  
	            }  
	            // 音频消息  
	            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {  
	                respContent = "您发送的是音频消息！";  
	            }  
	            // 事件推送  
	            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {  
	                // 事件类型  
	                String eventType = requestMap.get("Event");  
	                // 订阅  
	                if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE) || eventType.equals(MessageUtil.EVENT_TYPE_SCAN)) { 
	                	//未关注时，qrscene_为前缀，后面为终端编码，已关注则无前缀
	                	String eventKey = requestMap.get("EventKey");
	                	String terminalNo = eventKey.replaceAll("\\D", "");
	                	respContent = terminalBind(fromUserName, terminalNo);
	                }
	                // 取消订阅  
	                else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {  
	                    //TODO 未绑定取消订阅、已绑定取消订阅两种情况
	                	DAOFactory.getIUserDAOInstance().unbendUser(fromUserName);
	                	logger.info(fromUserName + "用户取消关注，解除绑定成功！");
	                }
	                // 自定义菜单点击事件,注意,更新自定义菜单后，获取点击事件的key时有延迟,取消关注后再次关注可及时更新  
	                else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {  
	                    String key = requestMap.get("EventKey");
	                    logger.debug("key : " + key);
	                    //故障上报
	                    if(key.equals("1_1_fault_report")) {
	                    	respContent = faultReport(fromUserName);
	                    }
	                    //我的报障历史
	                    else if(key.equals("2_1_my_report")) {
	                    	respContent = reportCheck(fromUserName);
	                    }
	                    //终端信息查看
	                    else if(key.equals("3_1_check")) {
	                    	respContent = infoCheck(fromUserName);
	                    }
	                    //解除绑定
	                    else if(key.equals("3_2_unbend")) {
	                    	respContent = unbend(fromUserName);
	                    }
	                }  
	            }  
	  
	            textMessage.setContent(respContent);  
	            respMessage = MessageUtil.textMessageToXml(textMessage);  
	        } catch (Exception e) {  
	            logger.error(e.getMessage());
	        	e.printStackTrace();  
	        }  
	  
	        return respMessage; 
	}
	
	
	//绑定帮助消息
	private static String createBindHelpMsg(String bindLink) {
		StringBuilder builder = new StringBuilder();
		builder.append(SUBSCRIBE_MSG_HEADER);
		builder.append(NEWLINE);
		
		builder.append(NEWLINE);
		builder.append(SUBSCRIBE_MSG_BODY);
		builder.append(bindLink);
		builder.append(NEWLINE);
		
		builder.append(BIND_TIPS);
		return builder.toString();
	}
	/**
	 * 终端绑定
	 * @param openid
	 * @param terminalNo 
	 * @return
	 */
	private static String terminalBind(String openid, String terminalNo) {
		String respContent = null;
		User user = DAOFactory.getIUserDAOInstance().findById(openid);
		
		//该微信号未绑定过
		if(user == null) {
    		logger.debug("该微信号未绑定");
    		String timestamp = String.valueOf(System.currentTimeMillis());
    		String signature = SignUtil.createSignature(openid, MpInfo.TOKEN, timestamp);
    		String bindLink = "<a href=\"" + MpInfo.HOST + "/servlet/BindServlet?terminalNo=%s&OpenId=%s&signature=%s&timestamp=%s\">点击这里，立即绑定您的终端</a>\n";
    		bindLink = String.format(bindLink, terminalNo, openid, signature, timestamp);
    		respContent = createBindHelpMsg(bindLink);
    		logger.debug("绑定确认url: " + respContent);
    	}
		//已绑定
    	else {
    		logger.debug("该微信号已绑定过");
    		respContent = "请勿重复绑定";
    	}
    		
		return respContent;
	}
	/**
	 * 故障上报历史信息查看
	 * @param fromUserName
	 * @return
	 */
	private static String reportCheck(String openid) {
		String respContent = null;
		User user = DAOFactory.getIUserDAOInstance().findById(openid);
		
		//该微信号未绑定过
		if(user == null) {
    		logger.debug("该微信号未绑定");
    		respContent = createBindHelpMsg(NEWLINE);
    		logger.debug("绑定确认url: " + respContent);
    	}
		//已绑定
    	else {
    		logger.debug("该微信号已绑定过");
    		String timestamp = String.valueOf(System.currentTimeMillis());
    		String signature = SignUtil.createSignature(openid, MpInfo.TOKEN, timestamp);
    		respContent = "<a href=\"" + MpInfo.HOST + "/my_report.jsp\">请戳这里</a>查看故障上报历史信息！";
    		respContent = String.format(respContent, openid, timestamp, signature);
    	}
    		
		return respContent;
	}
	/**
	 * 解除绑定
	 * @param openid
	 * @return
	 */
	private static String unbend(String openid) {
		String respContent = null;
		User user = DAOFactory.getIUserDAOInstance().findById(openid);
		//该微信号未绑定过
		if(user == null) {
    		logger.debug("该微信号未绑定");
    		respContent = createBindHelpMsg(NEWLINE);
    	}
		//已绑定
    	else {
    		logger.debug("该微信号已绑定过");
    		//解除绑定成功
    		if(DAOFactory.getIUserDAOInstance().unbendUser(openid)) {
    			logger.info(openid + " 解除绑定成功");
    			respContent = "成功解除绑定！";
    		}
    		else {
    			logger.info(openid + " 解除绑定失败");
    			respContent = "解除绑定失败！";
    		}
    	}
    		
		return respContent;
	}
	/**
	 * 故障上报
	 * @param terminalNo 
	 * @param fromUserName
	 * @return
	 */
	private static String faultReport(String openid) {
		String respContent = null;
		User user = DAOFactory.getIUserDAOInstance().findById(openid);
		
		//该微信号未绑定过
		if(user == null) {
    		logger.debug("该微信号未绑定");
    		respContent = createBindHelpMsg(NEWLINE);
    	}
		//已绑定
    	else {
    		logger.debug("该微信号已绑定过");
    		String timestamp = String.valueOf(System.currentTimeMillis());
    		String signature = SignUtil.createSignature(openid, MpInfo.TOKEN, timestamp);
    		respContent = "<a href=\"" + MpInfo.HOST + "/servlet/FaultReportServlet?OpenId=%s&timestamp=%s&signature=%s\">请戳这里</a>进行故障上报！";
    		respContent = String.format(respContent, openid, timestamp, signature);
    	}
    		
		return respContent;
	}
	/**
	 * 个人信息查看，若该微信号已绑定，则返回个人信息，若未绑定则返回绑定url
	 * @param fromUserName
	 * @return
	 */
	private static String infoCheck(String openid) {
		String respContent = null;
		User user = DAOFactory.getIUserDAOInstance().findById(openid);
		//该微信号未绑定过
		if(user == null) {
    		logger.debug("该微信号未绑定");
    		respContent = createBindHelpMsg(NEWLINE);
    	}
		//已绑定
    	else {
    		logger.debug("该微信号已绑定过");
    		JSONObject jsonObject = CoreServiceFactory.getInstance().userInfoGet(user.getOpenid());
    		WechatUser wechatUser = (WechatUser) JSONObject.toBean(jsonObject, WechatUser.class);
    		
    		respContent = "OpenId: " + user.getOpenid()+ "\n" + 
					"终端编码：" + user.getTerminalNo() + "\n" +
					"销售员号：" + user.getSalerNo() + "\n" +
					"密码： " + user.getPassword() + "\n" +
					"昵称：" + wechatUser.getNickname() + "\n";
    	}
    		
		return respContent;
	}
}
